import { createRouter, createWebHistory } from 'vue-router'
import {getAuthToken} from "@/utils/auth.js";

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/',
    component: () => import('../layout/Layout.vue'),
    children: [
      {
        path: '',
        name: 'Home',
        component: () => import('../views/Home.vue')
      },
      {
        path: 'materials',
        name: 'Materials',
        component: () => import('../views/material/MaterialList.vue')
      },
      {
        path: 'materials/:id',
        name: 'MaterialDetail',
        component: () => import('../views/material/MaterialDetail.vue')
      },
      {
        path: 'forum',
        name: 'Forum',
        component: () => import('../views/forum/ForumList.vue')
      },
      {
        path: 'forum/post/:id',
        name: 'PostDetail',
        component: () => import('../views/forum/PostDetail.vue')
      },
      {
        path: 'forum/create',
        name: 'CreatePost',
        component: () => import('../views/forum/CreatePost.vue')
      },
      {
        path: 'announcements',
        name: 'Announcements',
        component: () => import('../views/announcement/AnnouncementList.vue')
      },
      {
        path: 'announcements/:id',
        name: 'AnnouncementDetail',
        component: () => import('../views/announcement/AnnouncementDetail.vue')
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('../views/user/Profile.vue')
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = getAuthToken();
  if (to.path !== '/login' && to.path !== '/register' && !token) {
    next('/login')
  } else {
    next()
  }
})

export default router
